<template>
  <div v-if="hasError" class="error-boundary">
    <div class="error-content">
      <h2>页面加载失败</h2>
      <p>{{ errorMessage }}</p>
      <div class="error-actions">
        <button @click="handleRetry" class="retry-btn">重新加载</button>
        <button @click="handleGoHome" class="home-btn">返回首页</button>
      </div>
    </div>
  </div>
  <div v-else>
    <slot />
  </div>
</template>

<script>
export default {
  name: 'ErrorBoundary',
  data() {
    return {
      hasError: false,
      errorMessage: '页面加载失败，请重试'
    }
  },
  errorCaptured(error, instance, info) {
    console.error('ErrorBoundary捕获到错误:', error, info)
    
    // 检查是否是动态导入错误
    if (error.message && error.message.includes('Failed to fetch dynamically imported module')) {
      this.errorMessage = '组件文件加载失败，可能是网络问题或文件不存在'
    } else if (error.message && error.message.includes('Cannot read properties of undefined')) {
      this.errorMessage = '组件初始化失败，请刷新页面重试'
    } else {
      this.errorMessage = error.message || '页面加载失败，请重试'
    }
    
    this.hasError = true
    return false // 阻止错误继续传播
  },
  methods: {
    handleRetry() {
      this.hasError = false
      this.errorMessage = '页面加载失败，请重试'
      window.location.reload()
    },
    handleGoHome() {
      window.location.href = '/'
    }
  }
}
</script>

<style lang="scss" scoped>
.error-boundary {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 20px;
  background-color: #f5f5f5;
}

.error-content {
  text-align: center;
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-width: 500px;
}

h2 {
  color: #f56c6c;
  margin-bottom: 16px;
}

p {
  color: #666;
  margin-bottom: 24px;
  line-height: 1.5;
}

.error-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.retry-btn {
  background-color: #409eff;
  color: white;
  
  &:hover {
    background-color: #337ecc;
  }
}

.home-btn {
  background-color: #909399;
  color: white;
  
  &:hover {
    background-color: #73767a;
  }
}
</style>
